<template>
  <div>
    <!-- 概况 -->
    <div class="overview text-center">
      <div class="text-333 font-normal">
        <span>总得分：</span>
        <span
          class="font-semibold"
          :class="`text-${getScoreClass(stats.studentScore / stats.questionScore)}`"
          style="font-size: 0.5rem; line-height: 0.7rem"
          >{{ stats.studentScore }}</span
        >
        <span :class="`text-${getScoreClass(stats.studentScore / stats.questionScore)}`">分</span>
        <span>/{{ stats.questionScore }}分</span>
      </div>
    </div>
    <div v-for="(q, q_index) in stats.stem.sqs" :key="q_index">
      <Stem :data="q" />
      <div class="hr my-30px" v-show="q_index < stats.stem.sqs.length - 1"></div>
    </div>
  </div>
</template>

<script>
import Stem from '@/components/question/stem'
import { formatQuestionStem } from '@/utils/question'
import Mixin from '../mixin'

export default {
  components: {
    Stem
  },
  mixins: [Mixin],
  inject: ['_addTagClickHandler', '_removeTagClickHandler'],
  props: {
    question: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {}
  },
  computed: {
    stats() {
      const {
        questionId,
        stem: {
          info: { question }
        },
        answer,
        answerRecord: studentAnswer = {},
        studentScore,
        questionScore
      } = this.question

      let sqs = []
      question.forEach((q, index) => {
        const { ask = '', askaudio = '', analyze = '', std = [] } = q
        let answeraudio = ''

        try {
          const { anSqs } = studentAnswer

          answeraudio = anSqs[index].ans[0].anStudentUrl
        } catch (error) {}

        const templateSpeakerSelf = answeraudio
          ? `<span class="append-speaker"><img src="static/icons/speaker.png" data-question-id="${questionId}" data-audio-src="${answeraudio}" /></span>`
          : '<span class="text-FF4040">（未作答）</span>'
        const templateSpeakerStem = `<span class="append-speaker"><img src="static/icons/speaker.png" data-question-id="${questionId}" data-audio-src="${askaudio}" /></span>`

        let templateScore = `<div><span class="text-FF4040">${
          index + 1
        }.</span>${templateSpeakerSelf}</div>`
        let templateQuestion = `<div><span style="margin-right: 0.12rem;">问题：${ask.replace(
          /ets_th[0-9]\s/,
          `${index + 1}.`
        )}</span>${templateSpeakerStem}</div>`
        let templateAnalyze = `<div class="mt-20px">${analyze.replace(/^<\/br>/, '')}</div>`
        let templateAnswer = `<div class="mt-20px text-30C9A1">参考答案：${std
          .map((s) => `</br>● ${s.value}`)
          .join('')}</div>`

        try {
          const { anSqs } = studentAnswer

          const { studentScore: score = 0, questionScore: totalScore = 0 } = anSqs[index].ans[0]
          templateScore = `<div><span class="text-${this.getScoreClass(score / totalScore)}">${
            index + 1
          }.（得分：${score}分/${totalScore}分）</span>${templateSpeakerSelf}</div>`
        } catch (error) {}

        const html = `<div>${templateScore}${templateQuestion}${templateAnalyze}${templateAnswer}</div>`
        sqs.push({
          html,
          og: null,
          sqs: [],
          type: '复合题'
        })
      })

      return {
        questionId,
        stem: formatQuestionStem({
          html: '<div></div>',
          og: null,
          sqs,
          type: '英语听说-听后回答'
        }),
        answer,
        studentAnswer,
        studentScore: studentScore ? studentScore : 0,
        questionScore: questionScore ? questionScore : 0
      }
    }
  },
  mounted() {
    this._addTagClickHandler('img', this.handleImgClick)
  },
  beforeDestroy() {
    this._removeTagClickHandler('img', this.handleImgClick)
  },
  methods: {
    handleImgClick(node) {
      const { currentSrc = '' } = node
      if (currentSrc.indexOf('speaker.png') != -1) {
        const { audioSrc, questionId } = node.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          this.$message.error('未作答')
          return
        }

        if (questionId === this.question.questionId) {
          this.playAudio(node, audioSrc)

          const components = this.$parent.$parent.$refs
          for (let key in components) {
            if (Array.isArray(components[key]) && components[key].length > 0) {
              const component = components[key][0]
              const {
                question: { questionId: _questionId }
              } = component
              if (questionId != _questionId) {
                component.audioPlayer.pause()
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.overview {
  font-size: 20px;
}

/deep/ .append-speaker {
  display: inline-block;
  width: 46px;
  height: 46px;
  position: relative;

  img {
    width: 46px;
    height: 46px;
    position: absolute;
    top: 50%;
    transform: translateY(-24%);
  }

  .playing {
    @keyframes play {
      0% {
        opacity: 0.5;
      }

      25% {
        opacity: 0.25;
      }

      50% {
        opacity: 0.5;
      }

      75% {
        opacity: 0.75;
      }

      100% {
        opacity: 1;
      }
    }

    animation: play 1s ease-in-out infinite backwards;
  }
}

.hr {
  height: 1px;
  background: #eee;
}
</style>
